<template>
  <!-- 培训管理 -->
  <div class="_pageContent">
    <!-- <dataFilter :data="filterData" url="/video/selectOne" @search="search" ref="dataFilterRef"></dataFilter> -->

    <!-- 添加 -->
    <div class="_operation_add">
      <div style="color: #999">
        <icon-list />
        视频列表
      </div>
      <div style="display: flex; flex-direction: row; gap: 10px">
        <a-button type="primary" @click="addVideo">添加数据</a-button>
      </div>
    </div>

    <a-table :data="data">
      <template #columns>
        <a-table-column
          title="视频id"
          data-index="videoId"
          align="center"
        ></a-table-column>
        <a-table-column
          title="视频标题"
          data-index="name"
          align="center"
        ></a-table-column>
        <a-table-column
          title="视频时长"
          data-index="length"
          align="center"
        ></a-table-column>
        <a-table-column
          title="视频排序"
          data-index="sort"
          align="center"
        ></a-table-column>
        <a-table-column title="操作" data-index="operation" align="center">
          <template #cell="{ record }">
            <div class="_operation_wrapper">
              <span class="_operation_edit" @click="updataRecord(record)"
                >编辑</span
              >
              <span class="_operation_delete" @click="deleteRecord(record)"
                >删除</span
              >
            </div>
          </template>
        </a-table-column>
      </template>
    </a-table>
  </div>

  <!-- 添加 or 修改 -->
  <a-modal
    :visible="visible"
    :title="form.videoId ? '修改视频' : '添加视频'"
    @ok="handleOk"
    @cancel="visible = false"
  >
    <a-form :model="form" :rules="rules" ref="formRef">
      <a-form-item label="视频">
        <a-upload
          v-model:file-list="fileList"
          name="file"
          :action="url + '/file/upload'"
          accept="video/*"
          :limit="1"
          @success="videoSuccess"
          @before-upload="handleBeforeUpload"
          :onProgress="handleUploadProgress"
          @on-before-remove="beforeRemove"
        >
        </a-upload>
      </a-form-item>
      <a-form-item v-show="uploadProgress != 0" :label="uploadProgress < 1 ? '进度':'解析中'" >
        <a-progress v-show="uploadProgress < 1" :percent="uploadProgress" :style="{ width: '100%' }" />
        <div v-show="uploadProgress === 1">
            <icon-loading />
        </div>
      </a-form-item>
      <a-form-item label="标题" field="name">
        <a-input v-model="form.name" />
      </a-form-item>
      <a-form-item label="排序" field="sort">
        <a-input v-model="form.sort" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup>
import { onMounted, ref } from "vue";
import {
  postVideoList,
  postDeleteVideo,
  postAddVideo,
  postUpdateVideo,
} from "../../../api/video";
import { Modal, Message } from "@arco-design/web-vue";
// 上传url
const url = import.meta.env.VITE_APP_API_URL;
const imgUrl = import.meta.env.VITE_APP_IMG_URL;

// 视频数据
const data = ref([]);

// 获取视频数据
function videoList() {
  postVideoList({}).then((res) => {
    data.value = res.data;
  });
}
// 弹窗控制
const visible = ref(false);
// 表单数据
const form = ref({
  name: null,
  url: null,
  length: null,
  sort: null,
});
let uploadProgress = ref(0);

// 获取视频时长
function getVideoLength(url) {
  return new Promise((resolve, reject) => {
    const video = document.createElement("video");
    video.src = imgUrl + url;
    video.addEventListener("loadedmetadata", () => {
      resolve(video.duration);
    });

    video.addEventListener("error", () => {
      reject(new Error("视频加载失败"));
    });
  });
}

const getLength = (file) => {
  return new Promise((resolve, reject) => {
    // 创建一个 FileReader 对象
    const reader = new FileReader();
    // 读取文件为 DataURL
    reader.readAsDataURL(file);
    // 当读取完成时触发
    reader.onload = () => {
      // 创建一个 HTMLVideoElement 对象
      const video = document.createElement('video');
      // 设置视频的源为 DataURL
      video.src = reader.result;
      // 监听 loadedmetadata 事件
      video.onloadedmetadata = () => {
        // 获取视频时长（秒）
        const duration = Math.floor(video.duration);
        form.value.length = duration;
        // 允许文件上传
        resolve(true);
      };
      // 监听错误事件
      video.onerror = () => {
        console.error('无法加载视频元数据');
        // 阻止文件上传
        reject(false);
      };
    };
    // 监听读取错误事件
    reader.onerror = () => {
      console.error('文件读取错误');
      // 阻止文件上传
      reject(false);
    };
  });
};

function handleUploadProgress(e) {
  uploadProgress.value = e.percent;
}

// 控制文件是否在上传中
const isUploading = ref(false);

function handleBeforeUpload(e) {
  isUploading.value = true;
  form.value.url = null;
  form.value.length = null;
  getLength(e);
  return true;
}

// 视频上传成功
function videoSuccess(res) {
  isUploading.value = false;
  const { response } = res;
  form.value.url = response.data;
  uploadProgress.value = 0;
//   getVideoLength(response.data)
//     .then((duration) => {
//       form.value.length = duration;
//     })
//     .catch((err) => {
//       console.error(err);
//       Message.error("时长获取失败");
//       form.value.length = 0;
//     });
}
// 删除视频
function beforeRemove() {
  fileList.value = [];
  form.value.url = null;
  form.value.length = null;
}
// 添加
function addVideo() {
  fileList.value = [];
  visible.value = true;
  form.value = {
    name: null,
    url: null,
    length: null,
    sort: null,
  };
}
// 编辑
function updataRecord(record) {
  visible.value = true;
  form.value = JSON.parse(JSON.stringify(record));
}
// 表单ref
const formRef = ref(null);
// 表单验证
const rules = ref({
  name: [{ required: true, message: "请输入视频标题" }],
  sort: [{ required: true, message: "请输入排序序号" }],
});
// 文件列表
const fileList = ref([]);
// 确定
function handleOk() {
  if (isUploading.value) {
    return Message.error("视频上传中，请稍后再试！");
  }
  if (!form.value.url) {
    return Message.error("请上传视频");
  }
  if (!form.value.length) {
    return Message.error("正在获取视频时长，请稍后再试！");
  }
  formRef.value
    .validate()
    .then((res) => {
      if (!res) {
        const apiMethod = form.value.videoId ? postUpdateVideo : postAddVideo;
        apiMethod(form.value).then((res) => {
          if (res.code === 200) {
            Message.success(form.value.videoId ? "修改成功" : "添加成功");
            videoList();
            visible.value = false;
            fileList.value = []; // 清空文件列表
          }
        });
      }
    })
    .catch((err) => {
      console.error("表单验证失败:", err);
    });
}
// 删除
function deleteRecord(record) {
  Modal.info({
    title: "提示",
    content: "确定删除该数据吗？",
    closable: true,
    onOk: () => {
      postDeleteVideo(record.videoId).then((res) => {
        Message.success("删除成功");
        videoList();
      });
    },
  });
}
// 搜索
function search(res) {
  data.value = res.data;
}

onMounted(() => {
  videoList();
});
</script>
<style scoped>
._operation_wrapper {
  display: flex;
  gap: 10px;
  justify-content: center;
}

._operation_edit {
  color: #4588ff;
  cursor: pointer;
}

._operation_delete {
  color: #ff6a36;
  cursor: pointer;
}

._operation_add {
  margin-bottom: 10px;

  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style>